package com.bbseguros.pesquisador.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * @author hmsilva
 *
 */
public class CSVFileCreator {
	Logger logger = Logger.getLogger(CSVFileCreator.class);
	public static final String DIR_NAME = "csv_temp";

	/**
	 * @param content
	 * @return
	 */
	public String generateCsvFile(String content){
		String file = "";
		String completePath = "";
		
		try{	
			file =  File.separator + DIR_NAME + File.separator + createFileName();
			logger.debug("file: "+file);
			
			completePath = getDir() + File.separator +  file;
			logger.debug("completePath: "+completePath);			
			
		    FileWriter writer = new FileWriter(completePath);
		    writer.append(content);
		    
		    writer.flush();
		    writer.close();
		    
		}catch(IOException e){
			 logger.error(e.getMessage(), e);
		}
		
		return completePath;
	}
	
	/**
	 * @return
	 */
	private String createFileName(){
		
		String fileName = "relatorio_"+System.currentTimeMillis()+".csv";
		logger.debug("fileName:"+fileName );
		
		return fileName;
	}
	
	/**
	 * @return
	 */
	private String getDir() {
		
		String toReturn = "";
		InputStream in = this.getClass().getResourceAsStream("/config.properties");
		Properties props = new Properties();
		
		try {
			props.load(in);
			in.close();
			
			toReturn = props.getProperty("dir_csv_file");
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.debug("DIR RECEIVED: " + toReturn);
		return toReturn;
	}
}
